package com.ljc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.ljc.annotation.AuthCheck;
import com.ljc.client.ApiPlatformClient;
import com.ljc.common.*;
import com.ljc.constant.CommonConstant;
import com.ljc.constant.RedisConstant;
import com.ljc.constant.UserConstant;
import com.ljc.exception.BusinessException;
import com.ljc.model.dto.interfaceinfo.InterfaceInfoAddRequest;
import com.ljc.model.dto.interfaceinfo.InterfaceInfoInvokeRequest;
import com.ljc.model.dto.interfaceinfo.InterfaceInfoQueryRequest;
import com.ljc.model.dto.interfaceinfo.InterfaceInfoUpdateRequest;
import com.ljc.model.entity.InterfaceCharging;
import com.ljc.model.entity.InterfaceInfo;
import com.ljc.model.entity.User;
import com.ljc.model.enums.InterfaceInfoStatusEnum;
import com.ljc.model.enums.InterfaceOperateEnum;
import com.ljc.model.vo.InterfaceInfoVO;
import com.ljc.service.InterfaceChargingService;
import com.ljc.service.InterfaceInfoService;
import com.ljc.service.UserService;
import com.ljc.utils.InterfaceRabbitMqUtils;
import com.ljc.utils.RedissonBloomFilterUtils;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.*;

/**
 * 接口管理
 *
 * @author ljc
 */
@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceInfoService;
    @Resource
    private UserService userService;
    @Resource
    private InterfaceChargingService interfaceChargingService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private InterfaceRabbitMqUtils interfaceRabbitMqUtils;
    @Resource
    private RedissonBloomFilterUtils redissonBloomFilterUtils;

    private static final ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(2,
            5,
            30,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(100));

    // region 增删改查

    /**
     * 创建
     */
    @PostMapping("/add")
    @GlobalTransactional(rollbackFor = Exception.class)
    public BaseResponse<Long> addInterfaceInfo(@RequestBody InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);
        // 校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, true);
        User loginUser = userService.getLoginUser(request);
        interfaceInfo.setUserId(loginUser.getId());
        boolean result = interfaceInfoService.save(interfaceInfo);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        // 将接口信息缓存到Redis中，使用消息队列保证 添加 操作的成功执行
        Long interfaceInfoId = interfaceInfo.getId();
        interfaceRabbitMqUtils.operateInterfaceInfo(interfaceInfoId, InterfaceOperateEnum.UPDATE.getValue());
        redissonBloomFilterUtils.addInterfaceToBloomFilter(interfaceInfoId);
        return ResultUtils.success(interfaceInfoId);
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @GlobalTransactional(rollbackFor = Exception.class)
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceInfoService.removeById(id);
        if (b) {
            // 数据库删除成功即可删除缓存，使用消息队列保证 删除 操作的成功执行
            interfaceRabbitMqUtils.operateInterfaceInfo(id, InterfaceOperateEnum.DELETE.getValue());
        }
        // TODO 删除接口信息，更新布隆过滤器。或者采用定时更新的方式
        return ResultUtils.success(b);
    }

    /**
     * 更新
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest interfaceInfoUpdateRequest,
                                                     HttpServletRequest request) {
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);
        // 参数校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, false);
        User user = userService.getLoginUser(request);
        long id = interfaceInfoUpdateRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        if (result) {
            // 更新缓存再Redis中的接口信息，使用消息队列保证 更新 操作的成功执行
            interfaceRabbitMqUtils.operateInterfaceInfo(interfaceInfo.getId(), InterfaceOperateEnum.UPDATE.getValue());
        }
        return ResultUtils.success(result);
    }

    /**
     * 根据 接口id 获取接口信息
     */
    @GetMapping("/get")
    public BaseResponse<InterfaceInfoVO> getInterfaceInfoById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 布隆过滤器防止缓冲穿透
        boolean isContain = redissonBloomFilterUtils.isContain(id);
        if (!isContain) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口不存在！");
        }
        // 根据 接口id 查询接口信息
        // 从缓存中查询接口信息
        CompletableFuture<InterfaceInfo> interfaceInfoFuture = CompletableFuture.supplyAsync(() -> {
            String interfaceInfoJson = stringRedisTemplate.opsForValue().get(RedisConstant.INTERFACE_INFO_PREFIX + id);
            InterfaceInfo interfaceInfo;
            if (StringUtils.isNotEmpty(interfaceInfoJson)) {
                interfaceInfo = new Gson().fromJson(interfaceInfoJson, InterfaceInfo.class);
            } else {
                interfaceInfo = interfaceInfoService.getById(id);
            }
            return interfaceInfo;
        }, EXECUTOR);
        CompletableFuture<InterfaceCharging> interfaceChargingFuture = CompletableFuture.supplyAsync(() ->
                interfaceChargingService.getOne(new QueryWrapper<InterfaceCharging>().eq("interfaceId", id)), EXECUTOR);
        // 获取异步任务结果
        InterfaceInfo interfaceInfo;
        try {
            interfaceInfo = interfaceInfoFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            log.error("异步获取接口信息出错！");
            throw new RuntimeException(e);
        }
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口不存在！");
        }
        // 获取异步任务结果
        InterfaceCharging interfaceCharging;
        try {
            interfaceCharging = interfaceChargingFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            log.error("异步获取接口收费信息出错！");
            throw new RuntimeException(e);
        }
        InterfaceInfoVO interfaceInfoVO = new InterfaceInfoVO();
        BeanUtils.copyProperties(interfaceInfo, interfaceInfoVO);
        // 如果 这个接口 是收费接口
        if (interfaceCharging != null) {
            // 设置计费规则、可调用次数、收费接口id
            interfaceInfoVO.setCharging(interfaceCharging.getCharging());
            interfaceInfoVO.setAvailablePieces(interfaceCharging.getAvailablePieces());
            interfaceInfoVO.setChargingId(interfaceCharging.getId());
        }
        return ResultUtils.success(interfaceInfoVO);
    }

    /**
     * 获取列表（仅管理员可使用）
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @GetMapping("/list")
    public BaseResponse<List<InterfaceInfo>> listInterfaceInfo(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        if (interfaceInfoQueryRequest != null) {
            BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        List<InterfaceInfo> interfaceInfoList = interfaceInfoService.list(queryWrapper);
        return ResultUtils.success(interfaceInfoList);
    }

    /**
     * 分页获取列表
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoByPage(InterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        long current = interfaceInfoQueryRequest.getCurrent();
        long size = interfaceInfoQueryRequest.getPageSize();
        String sortField = interfaceInfoQueryRequest.getSortField();
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        String description = interfaceInfoQuery.getDescription();
        // description 需支持模糊搜索
        interfaceInfoQuery.setDescription(null);
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);
        queryWrapper.like(StringUtils.isNotBlank(interfaceInfoQueryRequest.getName()), "name", interfaceInfoQueryRequest.getName());
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(interfaceInfoPage);
    }

    // endregion

    /**
     * 发布接口
     */
    @PostMapping("/online")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> onlineInterfaceInfo(@RequestBody IdRequest idRequest) {
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long interfaceId = idRequest.getId();
        Boolean isSucceed = interfaceInfoService.onlineInterfaceInfo(interfaceId);
        if (isSucceed) {
            // 同时消息队列异步更新缓存
            interfaceRabbitMqUtils.operateInterfaceInfo(interfaceId, InterfaceOperateEnum.UPDATE.getValue());
        }
        return ResultUtils.success(isSucceed);
    }

    /**
     * 下线接口
     */
    @PostMapping("/offline")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> offlineInterfaceInfo(@RequestBody IdRequest idRequest) {
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long interfaceId = idRequest.getId();
        Boolean isSucceed = interfaceInfoService.offlineInterfaceInfo(interfaceId);
        if (isSucceed) {
            // 同时消息队列异步更新缓存
            interfaceRabbitMqUtils.operateInterfaceInfo(interfaceId, InterfaceOperateEnum.UPDATE.getValue());
        }
        return ResultUtils.success(isSucceed);
    }

    /**
     * 测试接口调用
     */
    @PostMapping("/invoke")
    public BaseResponse<Object> invokeInterfaceInfo(@RequestBody InterfaceInfoInvokeRequest interfaceInfoInvokeRequest,
                                                    HttpServletRequest request) {
        if (interfaceInfoInvokeRequest == null || interfaceInfoInvokeRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = interfaceInfoInvokeRequest.getId();
        String userRequestParams = interfaceInfoInvokeRequest.getUserRequestParams();
        // 判断是否存在
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        if (interfaceInfo.getStatus() == InterfaceInfoStatusEnum.OFFLINE.getValue()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口已关闭");
        }
        User loginUser = userService.getLoginUser(request);
        String accessKey = loginUser.getAccessKey();
        String secretKey = loginUser.getSecretKey();
        // 用户调用次数校验在网关已经校验
        // 利用反射动态调用
        Object res = invokeInterfaceByReflect
                (ApiPlatformClient.class, interfaceInfo.getMethodName(), userRequestParams, accessKey, secretKey);
        if (res == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        if (res.toString().contains("Error request")) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "调用错误，请检查调用次数！");
        }
        return ResultUtils.success(res);
    }

    private Object invokeInterfaceByReflect(Class<ApiPlatformClient> clientClazz, String methodName,
                                            String userRequestParams, String accessKey, String secretKey) {
        try {
            // 1. 获取构造器，参数为ak,sk
            Constructor<?> apiClientConstructor = clientClazz.getConstructor(String.class, String.class);
            // 2. 构造出客户端
            ApiPlatformClient apiClient = (ApiPlatformClient) apiClientConstructor.newInstance(accessKey, secretKey);
            // 3. 找到要调用的方法
            Method[] methods = clientClazz.getMethods();
            for (Method method : methods) {
                if (method.getName().equals(methodName)) {
                    // 3.1 获取参数类型列表
                    Class<?>[] parameterTypes = method.getParameterTypes();
                    if (parameterTypes.length == 0) {
                        // 如果没有参数，直接调用
                        return method.invoke(apiClient);
                    }
                    // 如果有参数，构造参数后进行调用
                    Gson gson = new Gson();
                    Object parameter = gson.fromJson(userRequestParams, parameterTypes[0]);
                    return method.invoke(apiClient, parameter);
                }
            }
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "没有找到相应的方法！");
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "调用方法出错，可能是没有写请求参数！");
        }
    }

    /**
     * 下载 sdk
     */
    @GetMapping("/sdk")
    public void getSdk(HttpServletResponse response) throws IOException {
        // 获取要下载的文件
        String path = "/usr/local/backend/api-platform/api-client-sdk-0.0.1.jar";
        File file = new File(path);
        // 设置响应头
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
        // 将文件内容写入响应
        try (InputStream in = new BufferedInputStream(Files.newInputStream(Paths.get(path)));
             OutputStream out = response.getOutputStream()) {
            byte[] buffer = new byte[4096];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            out.flush();
        } catch (IOException e) {
            // 处理异常
            throw new IOException();
        }
    }

}
